package org.jgs1904.tieba.service.impl;

import org.jgs1904.tieba.entity.Comment;
import org.jgs1904.tieba.entity.Post;
import org.jgs1904.tieba.entity.User;
import org.jgs1904.tieba.repository.CommentRepository;
import org.jgs1904.tieba.repository.PostRepository;
import org.jgs1904.tieba.repository.UserRepository;
import org.jgs1904.tieba.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @author junki
 * @date 2020/5/12 14:40
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Comment add(Comment comment) {

        Optional<User> userOptional = userRepository.findById(comment.getUser().getId());
        if (!userOptional.isPresent()) {
            return null;
        }
        comment.setUser(userOptional.get());

        Optional<Post> postOptional = postRepository.findById(comment.getPost().getId());
        if (!postOptional.isPresent()) {
            return null;
        }
        comment.setPost(postOptional.get());

        comment.setCreateTime(new Date());

        return commentRepository.save(comment);

    }

}
